﻿Imports Microsoft.VisualBasic
Imports System.Web.Configuration
Imports System.ServiceModel.Configuration
Imports DotNetNuke.Modules.IWebCF
Imports System.Collections.Generic
Imports System.Xml

Namespace DotNetNuke.Modules.IWebCF

    Public Class IWebConfigController


        Private Shared _iwebConfig As System.Configuration.Configuration 

        ''' <summary>
        ''' Opens web.config in the IWebCF module folder.
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks>
        ''' This action requires full trust ! :(
        ''' - ITL 5/12/08
        ''' </remarks>
        Public Shared ReadOnly Property IwebConfig() As System.Configuration.Configuration
            Get

                If _iwebConfig Is Nothing Then

                    _iwebConfig = _
                        WebConfigurationManager.OpenWebConfiguration("~/DesktopModules/IWebCF")

                End If

                Return _iwebConfig
            End Get
        End Property
        Public Shared Function GetMaxRequestLength() As Long

            Dim runtimeSection As HttpRuntimeSection

            runtimeSection = TryCast(IwebConfig.GetSection("system.web/httpRuntime"), HttpRuntimeSection)

            If runtimeSection Is Nothing Then Return -1

            Return runtimeSection.MaxRequestLength

        End Function

        Private Shared Sub SaveConfig()


            Try

                IwebConfig.Save(ConfigurationSaveMode.Minimal, True)

                Dim xDoc As New System.Xml.XmlDocument()

                xDoc.Load(IwebConfig.FilePath)

                Dim servicenode As XmlNode = xDoc.SelectSingleNode("/configuration/system.web/webServices")

                servicenode.InnerText = ""

                xDoc.Save(IwebConfig.FilePath)

            Catch ex As ConfigurationException


            End Try

        End Sub

        Public Shared Sub SetMaxRequestLength(ByVal maxLengthInKB As Long, ByVal endpoint As String)

            Dim runtimeSection As HttpRuntimeSection

            runtimeSection = TryCast(IwebConfig.GetSection("system.web/httpRuntime"), HttpRuntimeSection)

            If runtimeSection Is Nothing Then Exit Sub

            runtimeSection.MaxRequestLength = maxLengthInKB

            Dim element As BasicHttpBindingElement = GetEndpointBindingElement(endpoint)

            element.MaxReceivedMessageSize = maxLengthInKB * 1024
            element.MaxBufferSize = maxLengthInKB * 1024
            element.ReaderQuotas.MaxArrayLength = maxLengthInKB * 1024


            SaveConfig()

        End Sub

        Public Shared Function GetSendReceiveTimeout(ByVal endpoint As String) As TimeSpan

            Dim element As BasicHttpBindingElement = GetEndpointBindingElement(endpoint)

            If element.ReceiveTimeout = element.SendTimeout OrElse _
                element.ReceiveTimeout > element.SendTimeout Then

                Return element.ReceiveTimeout

            Else

                Return element.SendTimeout

            End If

        End Function

        Public Shared Sub SetSendReceiveTimeout(ByVal timeout As TimeSpan, ByVal endpoint As String)

            Dim element As BasicHttpBindingElement = GetEndpointBindingElement(endpoint)

            element.ReceiveTimeout = timeout
            element.SendTimeout = timeout


            SaveConfig()

        End Sub



        ''' <summary>
        ''' Adds settings to web.config to create an endpoint for each interface.
        ''' </summary>
        ''' <remarks>
        ''' ITLackey 02.17.08
        '''</remarks>
        Public Shared Sub UpdateEndpointConfiguration()

          
            Dim services As ServicesSection = TryCast(IwebConfig.GetSection _
                ("system.serviceModel/services"), ServicesSection)

            If services IsNot Nothing Then

                Dim coreElement As ServiceElement = _
                    services.Services.Item("DotNetNuke.Modules.IWebCF.CoreService")


                If coreElement IsNot Nothing Then

                    coreElement.Endpoints.Clear()

                    Dim baseAddress As String = DAL.WCF_Setting()

                    Dim contracts As New List(Of Type)(GetType(CoreService).GetInterfaces())

                    For Each item As Type In contracts

                        AddItemToConfig(coreElement, item)

                    Next

                    SaveConfig()

                End If


            End If



        End Sub

        Private Shared Sub AddItemToConfig(ByVal coreElement As ServiceElement, ByVal item As Type)

            Dim coreEndpoint As ServiceEndpointElement = New ServiceEndpointElement()

            coreEndpoint.Contract = item.FullName

            Dim iwebcontracts As IWebContractAttribute()

            iwebcontracts = TryCast(item.GetCustomAttributes(GetType(IWebContractAttribute), False), IWebContractAttribute())

            If iwebcontracts IsNot Nothing AndAlso iwebcontracts.Length > 0 Then

                If Not String.IsNullOrEmpty(iwebcontracts(0).Address) Then

                    coreEndpoint.Address = New Uri(iwebcontracts(0).Address, UriKind.Relative)
                End If


                If Not String.IsNullOrEmpty(iwebcontracts(0).Binding) Then

                    coreEndpoint.Binding = iwebcontracts(0).Binding

                Else

                    coreEndpoint.Binding = CoreBindings.mexHttpBinding.ToString

                End If

                If Not String.IsNullOrEmpty(iwebcontracts(0).BindingConfiguration) Then

                    coreEndpoint.BindingConfiguration = iwebcontracts(0).BindingConfiguration

                Else

                    coreEndpoint.BindingConfiguration = CoreBindingConfigurations.DefaultBinding

                End If


                If Not String.IsNullOrEmpty(iwebcontracts(0).Name) Then

                    coreEndpoint.Name = iwebcontracts(0).Name

                Else

                    coreEndpoint.Name = item.Name

                End If


            Else

                coreEndpoint.Address = New Uri(item.Name, UriKind.Relative)

                coreEndpoint.Name = item.Name

                coreEndpoint.Binding = CoreBindings.mexHttpBinding.ToString

                coreEndpoint.BindingConfiguration = CoreBindingConfigurations.DefaultBinding

            End If


            coreElement.Endpoints.Add(coreEndpoint)
        End Sub

        Private Shared Function GetEndpointBindingElement(ByVal endpoint As String) As BasicHttpBindingElement


            Dim bindings As BindingsSection = _
                TryCast(IwebConfig.GetSection("system.serviceModel/bindings"), BindingsSection)

            For Each element As BasicHttpBindingElement In bindings.BasicHttpBinding.Bindings


                If element.Name = endpoint Then

                    Return element

                End If

            Next

            Return New BasicHttpBindingElement(endpoint)

        End Function

    End Class

End Namespace
